package register

import (
	"bytes"
	"encoding/gob"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"sync"
	"time"
)

type Record struct {
	Path string `msgpack: "1"`
	Pos  int64 `msgpack: "2"`
}

type Register struct {
	Mreg  map[string]Record
	Mutex sync.RWMutex
}

var (
	Reg  *Register
	file *os.File
	err  error
)

func Init(path string) {
	// 读取文件
	if path == "" {
		path = "."
	} else {
		_, err := os.Stat(path)
		if err != nil && os.IsNotExist(err) {
			err = os.MkdirAll(path, os.ModePerm)
			if err != nil {
				fmt.Println("创建目录失败: ", err)
			}
		}
	}
	path = filepath.Join(path, ".sincedb")
	file, err = os.OpenFile(path, os.O_CREATE|os.O_WRONLY, os.ModePerm)
	if err != nil {
		fmt.Println("打开文件失败: ", err)
	}
	// 读取所有的内容
	b, err := ioutil.ReadFile(path)
	if err != nil {
		fmt.Println("读取文件失败: ", err)
	}
	Reg = &Register{
		Mreg: make(map[string]Record),
	}
	if len(b) > 0 {
		dec := gob.NewDecoder(bytes.NewBuffer(b))
		err = dec.Decode(&Reg.Mreg)
		if err != nil {
			fmt.Println("解析文件错误: ", err)
		}
	}
	Reg.Sync()
}

func (reg Register) Sync() {
	tick := time.Tick(2 * time.Second)
	go func() {
		for {
			<-tick
			buf := new(bytes.Buffer)
			enc := gob.NewEncoder(buf)
			err := enc.Encode(reg.Mreg)
			if err != nil {
				fmt.Println("序列化错误: ", err)
				continue
			}
			b := buf.Bytes()
			file.Seek(0, 0)
			_, e := file.Write(b)
			if e != nil {
				fmt.Println("写入文件失败: ", e)
			}
			file.Sync()
		}
	}()
}
